<template>
  <el-dialog :model-value="dialogVisible" :title="dialogTitle" width="40%" @close="handleClose">
    <el-form :model="form" label-width="70px" ref="formRef" :rules="rules">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.username" />
      </el-form-item>
      <el-form-item label="密码" prop="password" v-if="dialogTitle === '添加用户'">
        <el-input v-model="form.password" type="password" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" />
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="form.mobile" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm(formRef)">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { defineEmits, ref, watch } from 'vue'
import { addUser, editUser } from '@/api/user.js'
import { ElMessage } from 'element-plus'
import { useI18n } from 'vue-i18n'

// i18n
const i18n = useI18n()

const emits = defineEmits(['update:modelValue', 'change'])

const handleClose = () => {
  emits('update:modelValue', false)
}
const handleConfirm = (formEl) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      props.dialogTitle === '添加用户' ? await addUser(form.value) : await editUser(form.value)
      ElMessage({
        message: i18n.t('message.updeteSuccess'),
        type: 'success',
      })
      emits('change')
      handleClose()
    } else {
      return false
    }
  })
}

const props = defineProps({
  dialogTitle: {
    type: String,
    default: '',
    required: true,
  },
  dialogTabValue: {
    type: Object,
    default: () => {},
  },
})

const formRef = ref('')

const form = ref({
  username: '',
  password: '',
  email: '',
  mobile: '',
})

const rules = ref({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 5, message: '用户名长度在3-5之间', trigger: 'blur' },
  ],
  password: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'blur',
    },
  ],
  email: [
    {
      required: true,
      message: '请输入邮箱',
      trigger: 'blur',
    },
    {
      type: 'email',
      message: '请输入正确的邮箱',
      trigger: ['blur', 'change'],
    },
  ],
  mobile: [
    {
      required: true,
      message: '请输入手机号',
      trigger: 'blur',
    },
    // {
    //   pattern: ''
    // }
  ],
})

watch(
  () => props.dialogTabValue,
  () => {
    form.value = props.dialogTabValue
  },
  {
    deep: true,
    immediate: true,
  }
)
</script>

<style lang="scss" scoped></style>
